import pandas as pd
import numpy as np
import os
import json,pickle
from collections import OrderedDict
from rdkit import Chem
from rdkit.Chem import MolFromSmiles
import networkx as nx
from utils import *



def atom_features(atom):
    return np.array(one_of_k_encoding_unk(atom.GetSymbol(),
                                          ['C', 'N', 'O', 'S', 'F', 'Si', 'P', 'Cl', 'Br', 'Mg', 'Na', 'Ca', 'Fe', 'As',
                                           'Al', 'I', 'B', 'V', 'K', 'Tl', 'Yb', 'Sb', 'Sn', 'Ag', 'Pd', 'Co', 'Se',
                                           'Ti', 'Zn', 'H', 'Li', 'Ge', 'Cu', 'Au', 'Ni', 'Cd', 'In', 'Mn', 'Zr', 'Cr',
                                           'Pt', 'Hg', 'Pb', 'Unknown']) +
                    one_of_k_encoding(atom.GetDegree(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) +
                    one_of_k_encoding_unk(atom.GetTotalNumHs(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) +
                    one_of_k_encoding_unk(atom.GetImplicitValence(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) +
                    [atom.GetIsAromatic()])
def one_of_k_encoding(x, allowable_set):
    if x not in allowable_set:
        raise Exception("input {0} not in allowable set{1}:".format(x, allowable_set))
    return list(map(lambda s: x == s, allowable_set))
def one_of_k_encoding_unk(x, allowable_set):
    """Maps inputs not in the allowable set to the last element."""
    if x not in allowable_set:
        x = allowable_set[-1]
    return list(map(lambda s: x == s, allowable_set))
def smile_to_graph(smile):
    # print("wrong smi:",smile)
    mol = Chem.MolFromSmiles(smile)
    # print(type(mol))

    c_size = mol.GetNumAtoms()

    features = []
    for atom in mol.GetAtoms():
        feature = atom_features(atom)
        features.append(feature / sum(feature))

    edges = []
    for bond in mol.GetBonds():
        edges.append([bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()])
    g = nx.Graph(edges).to_directed()
    edge_index = []
    for e1, e2 in g.edges:
        edge_index.append([e1, e2])

    return c_size, features, edge_index
def seq_cat(prot):
    x = np.zeros(max_seq_len)
    for i, ch in enumerate(prot[:max_seq_len]):
        x[i] = seq_dict[ch]
    return x

datasets=['spv_dataset_2_new_under_n1_1','spv_dataset_3_new_under_n1_1','spv_dataset_4_new_under_n1_1','spv_dataset_5_new_under_n1_1']
dirpath='data/csv_data/'


#从这里开始是读取csv,创建字符编码字典，即charsetdict
seq_voc = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
seq_dict = {v:i for i,v in enumerate(seq_voc)}
seq_dict_len = len(seq_dict)
max_seq_len = 1000

compound_iso_smiles = []
for dt_name in datasets:
    # opts = ['train','val','test']
    # opts = ['train', 'test']
    opts = ['test']
    for opt in opts:
        df = pd.read_csv( dirpath+ dt_name + '_' + opt + '.csv')
        # df = pd.read_excel('data/csv_data/' + dt_name + '_' + opt + '.xlsx')
        compound_iso_smiles += list( df['compound_iso_smiles'] )
        # print(list(df['compound_iso_smiles']))
"""
set() 函数创建一个无序不重复元素集，可进行关系测试，删除重复数据，还可以计算交集、差集、并集等。
"""
compound_iso_smiles = set(compound_iso_smiles)
smile_graph = {}
for smile in compound_iso_smiles:
    g = smile_to_graph(smile)
    smile_graph[smile] = g

#读取csv,创建pt文件

# convert to PyTorch data format
for dataset in datasets:
    processed_data_file_train = 'data/processed/' + dataset + '_train.pt'
    processed_data_file_test = 'data/processed/' + dataset + '_test.pt'
    processed_data_file_val = 'data/processed/' + dataset + '_val.pt'
    if ((not os.path.isfile(processed_data_file_train)) or (not os.path.isfile(processed_data_file_test))):
        # df = pd.read_csv('data/csv_data/' + dataset + '_train.csv')
        # train_drugs, train_prots,  train_Y = list(df['compound_iso_smiles']),list(df['target_sequence']),list(df['Y'])
        # XT = [seq_cat(t) for t in train_prots]
        # train_drugs, train_prots,  train_Y = np.asarray(train_drugs), np.asarray(XT), np.asarray(train_Y)

        df = pd.read_csv(dirpath + dataset + '_test.csv')
        # df = pd.read_excel('data/csv_data/' + dataset + '_test.xlsx')

        # df['Y']=0

        test_drugs, test_prots,  test_Y = list(df['compound_iso_smiles']),list(df['target_sequence']),list(df['Y'])
        XT = [seq_cat(t) for t in test_prots]
        test_drugs, test_prots,  test_Y = np.asarray(test_drugs), np.asarray(XT), np.asarray(test_Y)

        # df = pd.read_csv('data/csv_data/' + dataset + '_val.csv')
        # val_drugs, val_prots, val_Y = list(df['compound_iso_smiles']), list(df['target_sequence']), list(df['Y'])
        # XT = [seq_cat(t) for t in val_prots]
        # val_drugs, val_prots, val_Y = np.asarray(val_drugs), np.asarray(XT), np.asarray(val_Y)

        # make data PyTorch Geometric ready
        # print('preparing ', dataset + '_train.pt in pytorch format!')
        # train_data = TestbedDataset(root='data', dataset=dataset+'_train', xd=train_drugs, xt=train_prots, y=train_Y,smile_graph=smile_graph)

        print('preparing ', dataset + '_test.pt in pytorch format!')
        test_data = TestbedDataset(root='data', dataset=dataset+'_test', xd=test_drugs, xt=test_prots, y=test_Y,smile_graph=smile_graph)

        # print('preparing ', dataset + '_val.pt in pytorch format!')
        # val_data = TestbedDataset(root='data', dataset=dataset+'_val', xd=val_drugs, xt=val_prots, y=val_Y,smile_graph=smile_graph)

        print(processed_data_file_train, ' and ', processed_data_file_test,' and ', processed_data_file_val, ' have been created')
    else:
        print(processed_data_file_train, ' and ', processed_data_file_test, ' are already created')
